import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class ServerUDP extends Thread
{
    @Override
    public void run()
    {
        MulticastSocket s;
        DatagramPacket packet;
        byte[] data;
        String msg, ip;

        try
        {
            s = new MulticastSocket(Constants.UDP_PORT);
            s.joinGroup(InetAddress.getByName(Constants.UDP_MULTICAST));
            ip = new String(InetAddress.getLocalHost().getHostAddress());
            
            while(true)
            {
                System.out.println("Server UDP waiting requests...");
                data = new byte[Constants.DATAGRAM_LENGHT];
                packet = new DatagramPacket(data,data.length);
                s.receive(packet);
                
                System.out.println("Recebi pedido de " + packet.getAddress().getHostAddress());
                
                msg = new String(packet.getData(),0,packet.getLength());
                
                if(msg.equals(Constants.REQUEST))
                {
                    packet = new DatagramPacket(ip.getBytes(),ip.length(),packet.getAddress(),packet.getPort());
                    s.send(packet);
                }
            }
        }
        catch(Exception e){System.out.println("UDP: " + e);}
    }
}